package com.suwish.pc.ui.component;

import static com.suwish.pc.util.ResourceUtils._Icon;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import com.android.ddmlib.FileListingService.FileEntry;
import com.android.ddmlib.IDevice;
import com.suwish.device.util.DeviceUtils;
import com.suwish.pc.ui.component.list.FileListCellEntry;
import com.suwish.pc.ui.component.list.FileListCellRenderer;
import com.suwish.pc.ui.util.UIHelper;
import com.suwish.pc.util.StringUtils;

/**
 * 
 * 
 * @author Min
 *
 */
public class UIRemoteFileExplorer extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JList fileList = null;
	private DefaultListModel listModel = null;
	private FileEntry root = null; //为了将来实现定位
	
	private IDevice device = null;
	//缓存什么，看情况再用
	private Map<FileEntry, List<FileEntry>> cache = new HashMap<FileEntry, List<FileEntry>>();
	
	private JPanel controlPanel = null;
	private JLabel pathLabel = null;
	
	private JButton upButton = null;
//	private JButton downButton = null;.
	private JButton rootButton = null;
	
	private JButton upLoadButton = null;
	private JButton downLoadButton = null;
	
	private JButton reFreshButton = null;
	public UIRemoteFileExplorer(){
		this(null);
	}
	public UIRemoteFileExplorer(IDevice device){
		this(device, null);
	}
	public UIRemoteFileExplorer(IDevice device, FileEntry root){
		initUI();
		this.device = device;
		this.root = root == null ? DeviceUtils.getRootEntry(device) : root;		
		initData(this.root);
		initEvent();
	}
	private void initEvent(){
		upButton.addActionListener(new AbstractAction() {			
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
				if(root.isRoot()) return;
				try{
					upButton.setEnabled(false);
					initData(root.getParent());
				}catch(Exception ex){
					ex.toString();
				}finally{
					upButton.setEnabled(true);
				}
			}
		});
		rootButton.addActionListener(new AbstractAction() {		
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
				initData(DeviceUtils.getRootEntry(device));				
			}
		});
		reFreshButton.addActionListener(new AbstractAction() {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
				try{
					reFreshButton.setEnabled(false);
					initData(root);
				}catch(Exception ex){
					ex.toString();
				}finally{
					reFreshButton.setEnabled(true);
				}				
			}
		});
		
		final AbstractAction actionListsner = new AbstractAction() {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
//				if(!(e.getSource() instanceof JMenuItem)) return;
				String cmd = ((AbstractButton)e.getSource()).getActionCommand();
				if(StringUtils.isEmpty(cmd))return;
				FileListCellEntry cell = (FileListCellEntry)fileList.getSelectedValue();
				try{
					if(UIHelper.ACTION_FOLDER_OPEN.equals(cmd)){
						if(!cell.getFileEntry().isDirectory()) return;
						initData(cell.getFileEntry());
					}else if(UIHelper.ACTION_FILE_UPLOAD.equals(cmd)){
						UIHelper.uploadFile(device, root);
					}else if(UIHelper.ACTION_FILE_DOWNLOAD.equals(cmd)){
						if(cell.getFileEntry().isDirectory()) return;
						UIHelper.downloadFile(device, cell.getFileEntry());
					}
				}catch(Exception ex){
					ex.printStackTrace();
					UIHelper.showErrorDialog(getParent(), ex);
				}
			}
		};
		upLoadButton.addActionListener(actionListsner);
		downLoadButton.addActionListener(actionListsner);
		final JPopupMenu menu = new JPopupMenu();
		final JMenuItem openItem = new JMenuItem("Open", _Icon("fileopen_12x12.png"));
		menu.add(openItem);
		openItem.addActionListener(actionListsner);
		openItem.setActionCommand(UIHelper.ACTION_FOLDER_OPEN);
		menu.addSeparator();
		final JMenuItem upLoadItem = new JMenuItem("Upload", _Icon("upload_16x16.png"));
		menu.add(upLoadItem);
		upLoadItem.setActionCommand(UIHelper.ACTION_FILE_UPLOAD);
		upLoadItem.addActionListener(actionListsner);
		upLoadItem.setToolTipText("Upload file to current folder");
		final JMenuItem downLoadItem = new JMenuItem("Download", _Icon("download_16x16.png"));
		menu.add(downLoadItem);
		downLoadItem.setActionCommand(UIHelper.ACTION_FILE_DOWNLOAD);
		downLoadItem.addActionListener(actionListsner);
		fileList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2 && !e.isPopupTrigger()){
				  FileListCellEntry cell = (FileListCellEntry)fileList.getSelectedValue();
				  if(cell == null || !cell.getFileEntry().isDirectory()) return;
				  initData(cell.getFileEntry());
				}
			}
			@Override
			public void mouseReleased(MouseEvent e) {
				if(!e.isPopupTrigger()) return;
				int index = fileList.locationToIndex(e.getPoint());
				if(index == -1) return;
				fileList.setSelectedIndex(index);
				FileListCellEntry cell = (FileListCellEntry)fileList.getSelectedValue();
				if(cell == null)return;
				boolean isDir = cell.getFileEntry().isDirectory();
				openItem.setEnabled(isDir);
				downLoadItem.setEnabled(!isDir);
				menu.show(fileList, e.getX(), e.getY());
			}
		});
	}
	
//	private void openFileEntry(){}
//	public void 
	private void initData(FileEntry currentEntry){
		if(device == null|| currentEntry == null) return;
		try{
			root = currentEntry;
			pathLabel.setText("<html><div style='margin-left: 12px;font: 12px;'>" + currentEntry.getFullPath() + "</div></html>");
			FileEntry[] entrys = DeviceUtils.getChildrenEntry(device, currentEntry);
			listModel.removeAllElements();
			for(FileEntry entry : entrys){
				listModel.addElement(new FileListCellEntry(entry));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void initUI(){
		setOpaque(false);
		setLayout(new BorderLayout());
		controlPanel = new JPanel(new BorderLayout(10, 0));
//		controlPanel.setPreferredSize(new Dimension(controlPanel.getWidth(), 30));
		pathLabel = new JLabel();
//		controlPanel.setOpaque(false);
		controlPanel.add(pathLabel, BorderLayout.CENTER);
		
		
		add(controlPanel, BorderLayout.NORTH);
		initControlButton();
		
		listModel = new DefaultListModel();
		fileList = new JList(listModel);
		fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		fileList.setCellRenderer(new FileListCellRenderer());
		add(new JScrollPane(fileList), BorderLayout.CENTER);
	}
	
	
	private void initControlButton(){
		JPanel controlButtonPanel = new JPanel();
		controlButtonPanel.setOpaque(false);
		controlButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		add(controlButtonPanel, BorderLayout.SOUTH);
		upButton = new JButton(_Icon("gtk-go-up_16x16.png"));
		upButton.setToolTipText("Go up");
		controlButtonPanel.add(upButton);
		rootButton = new JButton(_Icon("gtk-goto-top_16x16.png"));
		rootButton.setToolTipText("Go /");
		controlButtonPanel.add(rootButton);
		upLoadButton = new JButton(_Icon("upload_16x16.png"));
		upLoadButton.setToolTipText("Upload");
		upLoadButton.setActionCommand(UIHelper.ACTION_FILE_UPLOAD);
		controlButtonPanel.add(upLoadButton);
		downLoadButton = new JButton(_Icon("download_16x16.png"));
		downLoadButton.setToolTipText("DownLoad");
		downLoadButton.setActionCommand(UIHelper.ACTION_FILE_DOWNLOAD);
		controlButtonPanel.add(downLoadButton);
		reFreshButton = new JButton(_Icon("reload_16x16.png"));
		controlButtonPanel.add(reFreshButton);
	}
}
